package com.example.finger.dialog;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.finger.FingerHelper;
import com.example.finger.R;
import com.example.finger.SerialPortUtil;
import com.example.finger.bean.TaskSheet;
import com.example.finger.rules.FingerLib;
import com.example.finger.util.MatchFinger;
import com.google.gson.Gson;
import com.lyxmaster.lib.toasty.Toasty;
import com.lyxmaster.lib.util.DataConfig;
import com.lyxmaster.lib.view.BaseActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by LYX on 2018/11/26.
 */

public class OpenLockDialog extends BaseDialog {
    private Context context;
    private List<String> list = new ArrayList<>();

    private FingerLib m_szHost = FingerHelper.getInStance().m_szHost;
    private int fingerIndex = 0;        //0 验证军官身份    1验证士兵身份
    private TaskSheet taskSheet;
    //是否通过指纹验证
    private boolean bCanOpen = false;

    private TextView textViewTitile;
    private TextView textViewTip;
    private TextView textViewOpen;
    private TextView textViewClose;
    private TextView textViewCancel;
    private TextView textViewNum;
    private TextView textViewStauts;
    private TextView textViewSuogan;

    private int caozuo = 0;

    private int SHIFENG = 1;
    private int JIEFENG = 2;

    @Override
    public View createView(Context context, LayoutInflater inflater, ViewGroup container) {
        this.context = context;
        return inflater.inflate(R.layout.dialog_open_lock, container, false);
    }

    public static OpenLockDialog getInstance(String title) {
        OpenLockDialog dialogFragment = new OpenLockDialog();
        dialogFragment.setCanceledBack(false);
        dialogFragment.setCanceledOnTouchOutside(false);

        Bundle args = new Bundle();
        args.putString("title", title);
        dialogFragment.setArguments(args);

        return dialogFragment;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        FingerHelper.getInStance().bOpeningLock = true;
        taskSheet = new Gson().fromJson(getArguments().getString("title"), TaskSheet.class);

        for (int i = 0; i < taskSheet.getPadLock().size(); i++) {
            list.add(String.valueOf(taskSheet.getPadLock().get(i).getId()));
        }

        textViewTitile = getView().findViewById(R.id.tv_title);
        textViewTip = getView().findViewById(R.id.tv_tip);
        textViewOpen = getView().findViewById(R.id.tv_open);
        textViewClose = getView().findViewById(R.id.tv_close);
        textViewCancel = getView().findViewById(R.id.tv_cancle);
        textViewNum = getView().findViewById(R.id.tv_num);
        textViewStauts = getView().findViewById(R.id.tv_status);
        textViewSuogan = getView().findViewById(R.id.tv_suogan);

        textViewTitile.setText("部位：" + taskSheet.getTask().getBuweiname());
        textViewTip.setText("请按下 军官人员 指纹");
        m_szHost.Run_CmdGetFeatureOfCapturedFP();

        m_szHost.setOnFingerDoneListener(new FingerLib.OnFingerDoneListener() {
            @Override
            public void OnGetMessage(String content) {
                if (content.startsWith("0")) {
                    switch (fingerIndex) {
                        case 0:
                            for (int i = 0; i < taskSheet.getOp1Finger().size(); i++) {
                                if (MatchFinger.match(DataConfig.hexStringToHexBytes(taskSheet.getOp1Finger().get(i).getData()), m_szHost.m_TemplateData)) {
                                    textViewTip.setText("请按下 士兵人员 指纹");
                                    FingerHelper.openLockOp1Index = i;
                                    Toasty.success(context, "匹配成功").show();
                                    new Timer().schedule(new TimerTask() {
                                        @Override
                                        public void run() {
                                            ((Activity) (context)).runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    fingerIndex = 1;
                                                    m_szHost.Run_CmdGetFeatureOfCapturedFP();
                                                }
                                            });
                                        }
                                    }, 1000);
                                    return;
                                }
                            }
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    ((Activity) (context)).runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            fingerIndex = 0;
                                            textViewTip.setText("请按下 军官人员 指纹");
                                            m_szHost.Run_CmdGetFeatureOfCapturedFP();
                                            Toasty.error(context, "匹配失败").show();
                                        }
                                    });
                                }
                            }, 1000);
                            break;
                        case 1:
                            for (int i = 0; i < taskSheet.getOp2FInger().size(); i++) {
                                if (MatchFinger.match(DataConfig.hexStringToHexBytes(taskSheet.getOp2FInger().get(i).getData()), m_szHost.m_TemplateData)) {
                                    FingerHelper.openLockOp2ndex = i;
                                    textViewTip.setText("认证成功，可开锁");
                                    bCanOpen = true;
                                    Toasty.success(context, "匹配成功").show();
                                    return;
                                }
                            }
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    ((Activity) (context)).runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            fingerIndex = 1;
                                            textViewTip.setText("请按下 士兵人员 指纹");
                                            m_szHost.Run_CmdGetFeatureOfCapturedFP();
                                            Toasty.error(context, "匹配失败").show();
                                        }
                                    });
                                }
                            }, 1000);
                            break;
                    }
                } else {
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            ((Activity) (context)).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    textViewTip.setText("获取失败,请再按一次");
                                    m_szHost.Run_CmdGetFeatureOfCapturedFP();
                                }
                            });
                        }
                    }, 1000);
                }
            }
        });

        //点击开锁
        textViewOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!list.contains(textViewNum.getText().toString())) {
                    Toasty.error(getContext(), "此挂锁不在任务单内").show();
                    return;
                }

                if (!bCanOpen) {
                    Toasty.error(context, "未通过指纹认证").show();
                    return;
                }
                try {
                    FingerHelper.getInStance().openLock(taskSheet, textViewNum.getText().toString());
                    caozuo = JIEFENG;
                    //开锁成功
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            ((Activity) (context)).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                   OpenLockDialog.this.dismiss();
                                }
                            });
                        }
                    }, 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toasty.error(getContext(), "开锁失败" + e.toString()).show();
                }
            }
        });

        textViewClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!list.contains(textViewNum.getText().toString())) {
                    Toasty.error(getContext(), "此挂锁不在任务单内").show();
                    return;
                }

                if (!bCanOpen) {
                    Toasty.error(context, "未通过指纹认证").show();
                    return;
                }

                try {
                    FingerHelper.getInStance().closeLock(taskSheet, textViewNum.getText().toString());
                    caozuo = SHIFENG;
                    //关锁成功
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            ((Activity) (context)).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    OpenLockDialog.this.dismiss();
                                }
                            });
                        }
                    }, 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toasty.error(getContext(), "关锁失败" + e.toString()).show();
                }
            }
        });

        textViewCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        SerialPortUtil.getInstance().setSCMDataReceiveListener(new SerialPortUtil.SCMDataReceiveListener() {
            @Override
            public void dataRecevie(final byte[] data) {
                ((Activity) (getContext())).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            byte[] num = new byte[8];
                            System.arraycopy(data, 3, num, 0, 8);
                            textViewNum.setText(new String(num, "US-ASCII"));

                            char[] suogan = DataConfig.invertUsingFor(DataConfig.bytes2BinaryStr(new byte[]{data[23]}).toCharArray());
                            char[] pwd = DataConfig.invertUsingFor(DataConfig.bytes2BinaryStr(new byte[]{data[24]}).toCharArray());
                            if (pwd[2] == '1') {
                                Toasty.error(getContext(), "密码错误").show();
                                return;
                            }

                            if (!(suogan[2] == '1')) {
                                textViewSuogan.setText("关闭");
                            } else {
                                textViewSuogan.setText("打开");
                            }

                            if ((suogan[1] == '1' && suogan[0] == '1') || (suogan[1] == '0' && suogan[0] == '0')) {
                                textViewStauts.setText("不定");
                            } else if (suogan[0] == '1') {
                                textViewStauts.setText("关锁");
                                if (caozuo == SHIFENG) {
                                    Toasty.success(getContext(), "关锁成功").show();
                                    caozuo = 0;
                                }

                            } else if (suogan[1] == '1') {
                                textViewStauts.setText("开锁");
                                if (caozuo == JIEFENG) {
                                    Toasty.success(getContext(), "开锁成功").show();
                                    caozuo = 0;
                                }
                            }

                            resetTimer();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }


    private Timer timerBtRecv = new Timer();
    private TimerTask timerTaskBtRecv;

    private void resetTimer() {
        if (timerTaskBtRecv != null) timerTaskBtRecv.cancel();
        timerTaskBtRecv = new TimerTask() {
            @Override
            public void run() {
                try {
                    ((Activity) (getContext())).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textViewNum.setText("");
                            textViewSuogan.setText("");
                            textViewStauts.setText("");
                        }
                    });
                } catch (Exception e) {

                }
            }
        };
        timerBtRecv.schedule(timerTaskBtRecv, 3000);
    }

    @Override
    public void dismiss() {
        SerialPortUtil.getInstance().setSCMDataReceiveListener(null);
        if (timerTaskBtRecv != null) timerTaskBtRecv.cancel();
        ((BaseActivity) (context)).hud.show("正在退出操作");
        m_szHost.setOnFingerListener(null);
        m_szHost.setOnFingerDoneListener(null);

        m_szHost.Run_CmdCancel();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                ((Activity) (getContext())).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((BaseActivity) (context)).hud.dismiss();
                        OpenLockDialog.super.dismiss();
                    }
                });
            }
        }, 2000);
    }
}
